package com.lge.clock.stopwatch;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;

/**
 * @author lge.com
 */
public class StopWatchDBAdapter 
{
	private static final String DATABASE_NAME = "stopwatch.db";
	private static final String DATABASE_TABLE = "lab";
	private static final int DATBASE_VERSION = 1;
	
	public static final String KEY_ID="_id";
	
	public static final String LAPCOUNT_NAME = "lapcount";
	public static final int LAPCOUNT_COLUMN = 1;
	public static final String LAPTIME_NAME1 = "laptime1";
	public static final int LAPTIME_COLUMN1 = 2;
	public static final String LAPTIME_NAME2 = "laptime2";
	public static final int LAPTIME_COLUMN2 = 3;
	
	private static final String DATABASE_CREATE = "create table " + DATABASE_TABLE + " (" + KEY_ID + 
			" integer primary key autoincrement, " + LAPCOUNT_NAME + " text not null, " + LAPTIME_NAME1 + " text not null, " + LAPTIME_NAME2 + " text not null); ";
	
	private SQLiteDatabase db;
	
	private final Context context;
	private StopWatchDBHelper dbHelper;
	
	public StopWatchDBAdapter(Context c)
	{
		context = c;
		dbHelper = new StopWatchDBHelper(context, DATABASE_NAME, null, DATBASE_VERSION);
	}
	
	public StopWatchDBAdapter open() throws SQLException
	{
		db = dbHelper.getWritableDatabase();
		return this;
	}
	
	public void close()
	{
		db.close();
	}
	
	public long insertEntry(LapValue lv)
	{
		ContentValues contentValues = new ContentValues();
		contentValues.put(LAPCOUNT_NAME, lv.getLap_count());
		contentValues.put(LAPTIME_NAME1, lv.getLap_time1());
		contentValues.put(LAPTIME_NAME2, lv.getLap_time2());
		return db.insert(DATABASE_TABLE, null, contentValues);
	}
	
	public boolean removeEntry()
	{
		return db.delete(DATABASE_TABLE, null, null) > 0;
	}
	
//	public Cursor getAllEntries()
//	{
//		return db.query(DATABASE_TABLE, new String[]{KEY_ID, LAPCOUNT_NAME, LAPTIME_NAME1, LAPTIME_NAME2}, null, null, null, null, null);
//	}
	
	/**
	 * @author lge.com
	 */
	public static class StopWatchDBHelper extends SQLiteOpenHelper
	{

		public StopWatchDBHelper(Context context, String name, CursorFactory factory, int version) 
		{
			super(context, name, factory, version);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(DATABASE_CREATE);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			// TODO Auto-generated method stub
			
		}

	}
}
